/**
 * 
 */
package com.wisdytech.linkdcs.equipment.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.bean.StandardResult;
import com.wisdytech.common.bean.event.EquipEvent;
import com.wisdytech.common.constants.CommonConstants;
import com.wisdytech.common.enums.ActionType;
import com.wisdytech.common.exception.ServiceException;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.linkdcs.account.dao.TtEqEquipmentAidDao;
import com.wisdytech.linkdcs.account.model.TtEqEquipmentAid;
import com.wisdytech.linkdcs.equipment.dao.IEqCollectionClientDao;
import com.wisdytech.linkdcs.equipment.dao.IEqEquipAlarmParamDao;
import com.wisdytech.linkdcs.equipment.dao.IEqEquipmentDao;
import com.wisdytech.linkdcs.equipment.dao.IEqModelDao;
import com.wisdytech.linkdcs.equipment.dao.IEqToClientDao;
import com.wisdytech.linkdcs.equipment.model.CollectionClient;
import com.wisdytech.linkdcs.equipment.model.EquipAlarmParam;
import com.wisdytech.linkdcs.equipment.model.EquipModel;
import com.wisdytech.linkdcs.equipment.model.Equipment;
import com.wisdytech.linkdcs.equipment.model.EquipmentToClient;
import com.wisdytech.linkdcs.equipment.service.IEquipmentRegisteredService;

/**
 * <p>
 * ClassName: 
 * </p>
 * <p>
 * Description: 
 * </p>
 * <p>
 * Author: kongming
 * </p>
 * <p>
 * Date: 2017-9-29
 * </p>
 */
@Service("equipmentRegisterService")
@Transactional
public class EquipmentRegisterServiceImpl extends BaseService<IEqEquipmentDao, Equipment> implements IEquipmentRegisteredService{
    /**
     * 注入设备dao
     */
    @Resource
    private IEqEquipmentDao equipDao;
    /**
     * 注入设备类别dao
     */
    @Resource
    private IEqModelDao modelDao;
    /**
     * 注入设备采集器Dao
     */
    @Resource
    private IEqCollectionClientDao clientDao;
    /**
     * 注入预警定义dao
     */
    @Resource
    private IEqEquipAlarmParamDao alarmParamDao;
    
    
    /**设备与终端关联表**/
    @Resource
    private IEqToClientDao etclientDao;
    
    /**处理设备注册事件推送*/
    @Autowired
    ApplicationContext applicationContext;
    
    @Resource
    private TtEqEquipmentAidDao ttEEquipmentAidDao;
    
    
    @Override
    public PageInfo<Equipment> listEquipmentRegisterByFilter(String modelCode, String equipCode, String equipName, Filter filter) {
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("modelCode", modelCode);
        queryMap.put("equipCode", equipCode);
        queryMap.put("equipName", equipName);
        List<Equipment> lists =
                super.beforeList(IEqEquipmentDao.class, filter).selectRegisterPage(queryMap);
        PageInfo<Equipment> equipModelPage=new PageInfo<>(lists);
        return equipModelPage;
    }

    @Override
    public StandardResult addEquipment(Equipment equipment, String loginName) {
        EntityWrapper<Equipment> ew =new EntityWrapper<>();
        //验证设备编号的唯一性
        List<Equipment> equipList;
        equipList = equipDao.selectPage(new Page<Equipment>(1, 1), ew.eq("EQUIP_CODE", equipment.getEquipCode()).eq("del_flag", CommonConstants.DEL_FLAG));
        if (!equipList.isEmpty()) {
            return StandardResult.getFailResult(CommonConstants.EQUIP_CODE);
        }
       equipment.setPkId(BaseUtil.getUUID());
       equipment.setDelFlag(CommonConstants.DEL_FLAG);
       equipment.setCreateUser(loginName);
       equipment.setCreateDate(new Date());
       equipment.setUpdateDate(new Date());

       equipment.setOperationId(equipment.getOperationName());
       int equipmentCount =equipDao.insert(equipment);
       if (equipmentCount<=0){
           throw new ServiceException("新增失败");
       }
       
       //推送设备新增事件
       List<String> equipIds=new ArrayList<>(); 
       equipIds.add(equipment.getPkId());
       List<String> equipCodes=new ArrayList<>(); 
       equipCodes.add(equipment.getEquipCode());
       EquipEvent event =new EquipEvent(this,equipIds,equipCodes, ActionType.ADD);
       event.setDealUser(loginName);
       applicationContext.publishEvent(event);
       
        return StandardResult.getSuccessResult();
    }

    @Override
    public StandardResult updateEquipment(Equipment equipment, String loginName) {
        EntityWrapper<Equipment> ew =new EntityWrapper<>();
        //验证设备编号的唯一性--修改功能
        List<Equipment> equipList;
        equipList = equipDao.selectPage(new Page<Equipment>(1, 1),ew.eq("EQUIP_CODE", equipment.getEquipCode()).ne("pk_id", equipment.getPkId()).eq("del_flag", CommonConstants.DEL_FLAG));
        if (equipList.size() > 0){
            return StandardResult.getFailResult(CommonConstants.EQUIP_CODE);
        }
        Equipment eq = equipDao.selectById(equipment.getPkId());
//        EquipModel model = modelDao.getEuipmentModelByEmModel(equipment.getModelCode());
//        CollectionClient collectClient = new CollectionClient();
//        collectClient =clientDao.getCollectionClientByModelId(model.getPkId());
//        equipment.setModelId(model.getPkId());
        equipment.setUpdateDate(new Date());
        equipment.setUpdateUser(loginName);
        equipment.setOperationId(equipment.getOperationName());
        int count = equipDao.updateById(equipment);
        if (count<=0) {
            throw new ServiceException("修改失败");
        }
        
        //推送设备新增事件
        List<String> equipIds=new ArrayList<>(); 
        equipIds.add(equipment.getPkId());
        List<String> equipCodes=new ArrayList<>(); 
        equipCodes.add(eq.getEquipCode());
        EquipEvent event =new EquipEvent(this,equipIds,equipCodes, ActionType.UPDATE);
        event.setDealUser(loginName);
        applicationContext.publishEvent(event);
        return StandardResult.getSuccessResult();
        
        
    }
    @Override
    public Equipment getEquipmentRegisterById(String id) {
       
        return equipDao.selectDetailById(id);
    }

    @Override
    public StandardResult delEquipmentById(String id,String loginName) {
        String[] ids = id.split(",");
        //设备编码列表
        List<String> equipCodes =new ArrayList<>();
        
        for (String pkId : ids) {
            //设备删除为假删除
            Equipment equipment = equipDao.selectById(pkId);
            int alarmParamCount = alarmParamDao.selectCount(new EntityWrapper<EquipAlarmParam>().eq("EQUIP_CODE", equipment.getEquipCode()).eq("del_flag", CommonConstants.DEL_FLAG));
            if  (alarmParamCount > 0) {
                return StandardResult.getFailResult(CommonConstants.EQUIPMENT_ALARM);
            }
            
            //设备关联终端个数
            int eqToClientNums =
            		etclientDao.selectCount(new EntityWrapper<EquipmentToClient>().eq("EQUIP_CODE", equipment.getEquipCode()));
            
            if (eqToClientNums>0) {
                return StandardResult.getFailResult(CommonConstants.EQUIPMENT_CONNECT);
            }
            
            
            equipment.setDelFlag(CommonConstants.DEL_FLAG_TRUE);
            int count = equipDao.updateById(equipment);
            if (count <= 0){
                throw new ServiceException("删除失败");
            }
            
            equipCodes.add(equipment.getEquipCode());
        }
        
        //推送设备新增事件
        List<String> equipIds=Arrays.asList(ids);
        EquipEvent event =new EquipEvent(this,equipIds,equipCodes, ActionType.UPDATE);
        event.setDealUser(loginName);
        applicationContext.publishEvent(new EquipEvent(this,equipIds,equipCodes, ActionType.DEL));
        
        
        return StandardResult.getSuccessResult();
    }

    @Override
    public List<Equipment> listAllEquipment(String modelId) {
        return equipDao.listAllEquipment(modelId);
    }
    
    @Override
    public List<Equipment> listAllEquipmentByModelCode(String modelCode) {
        return equipDao.listAllEquipmentByModelCode(modelCode);
    }
    
    
    @Override
    public List<Equipment> listAllEquipmentByOperationId(String operationId, String serach) {
        EntityWrapper<Equipment> ew = new EntityWrapper<>();
        if (StringUtils.isNotBlank(serach)) {
            ew.like("equip_code", serach);
        }
//        ew.eq("OPERATION_ID", operationId);
        ew.eq("del_flag", CommonConstants.DEL_FLAG);
        return equipDao.selectList(ew);
    }

    @Override
    public  Equipment getEquipmentByEquipCode(String equipCode) {
        return equipDao.getEquipmentByEquipCode(equipCode);
    }

    @Override
    public List<Equipment> selectByCilentId(String equipClientId) {
        return equipDao.selectByClientId(equipClientId);
    }

    @Override
    public PageInfo<Equipment> searchEquipmentByCode(Filter filter, String code) {
        EntityWrapper<Equipment> ew =new EntityWrapper<>();
        ew.eq("del_flag", CommonConstants.DEL_FLAG);
        ew.like("EQUIP_CODE", code, SqlLike.DEFAULT);
        ew.orderBy("CREATE_DATE", false);
        List<Equipment> list =
                super.beforeList(IEqEquipmentDao.class, filter).selectList(ew);
        
        return new PageInfo<Equipment>(list);
    }

    @Override
    public Equipment getEquipmentByEquipId(String equipId) {
//        EntityWrapper<Equipment> ew =new EntityWrapper<>();
//        ew.eq("del_flag", CommonConstants.DEL_FLAG);
//        ew.eq("pk_id", equipId);
//        Equipment equip = new Equipment();
        return equipDao.selectById(equipId);
    }

	@Override
	public Equipment equipCodeChangeByeqCode(String equipCode) {
		if(equipCode==null || equipCode=="") {
			return new Equipment();
		}
		return equipDao.equipCodeChangeByeqCode(equipCode);
	}

	@Override
	public PageInfo<Equipment> searchEquipByType(Filter filter,String search, String type,String equipCode) {
		// TODO Auto-generated method stub
		
		//查找设备工序
		String operationId="";
		if(StringUtils.isNotBlank(equipCode)) {
			Equipment  equipment =equipDao.getEquipmentByEquipCode(equipCode);
			operationId=equipment.getOperationId();
		}
		
		
		List<Equipment> list=this.beforeList(IEqEquipmentDao.class, filter)
				.searchEquipByType(search, type,operationId);
		return new PageInfo<Equipment>(list);
	}

	@Override
	public void delAidEquip(String equipCode, String aidEquipCode) {
		//删除已存在的辅助类设备
    	EntityWrapper<TtEqEquipmentAid> dew
				=new EntityWrapper<>();
		dew.eq("EQUIP_CODE", equipCode);
		dew.eq("AID_EQUIP_CODE", aidEquipCode);
		ttEEquipmentAidDao.delete(dew);
		
	}

}
